package com.atguigu.flinkSql2;


import com.atguigu.been.WaterSensor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.table.planner.expressions.Collect;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;


/**
 * @author wky
 * @create 2021-07-22-10:40
 */

// 聚合函数 不能在sql 语句中使用
public class Flink09_UDATF_TableAggregateFunction {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);
        //将默认时区从格林威治时区改为东八区
        Configuration configuration = tableEnvironment.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");
        //2.读取文件得到DataStream
        DataStreamSource<WaterSensor> waterSensorDataStreamSource = env.fromElements(
                new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        //3.将流转换为动态表
        Table table = tableEnvironment.fromDataStream(waterSensorDataStreamSource);


//        //不注册函数直接使用 只能在tableApi中使用
//        不起别名 直接用 f0 f1代替
//        table
//                .groupBy($("id"))
//                .flatAggregate(call(Top2.class,$("vc")))
//                .select($("id"),$("f0"),$("f1"))
////                .execute().print();
        //对列起别名
//        table
//                .groupBy($("id"))
//                .flatAggregate(call(Top2.class,$("vc")).as("value", "top"))
//                .select($("id"),$("value"),$("top"))
//                .execute().print();
//        注册函数 再使用 可以在sql语句中
//        tableEnvironment.createTemporarySystemFunction("top2",Top2.class);
//        table
//                .groupBy($("id"))
//                .flatAggregate(call("top2",$("vc")).as("value", "top"))
//                .select($("id"),$("value"),$("top")).execute().print();
//

        //todo sql 用不了


    }
    //定义一个类当做累加器，并声明第一和第二这两个值
    public static class vCTop2 {
        public Integer first = Integer.MIN_VALUE;
        public Integer second = Integer.MIN_VALUE;
    }


    ////自定义UDATF函数（多进多出）,求每个WaterSensor中最高的两个水位值
    public static class Top2 extends TableAggregateFunction<Tuple2<Integer, String>, vCTop2> {
        //创建累加器
        @Override
        public vCTop2 createAccumulator() {
            return new vCTop2();
        }
        //累加操作
        public void accumulate(vCTop2 acc , Integer value){
            if (value>acc.first){
                acc.second = acc.first;
                acc.first=value;
            }
            else if(value>acc.second){
                acc.second = value;
            }
        }

        //返回值
        public void emitValue(vCTop2 acc , Collector<Tuple2<Integer,String>> out){
            if (acc.first!=Integer.MIN_VALUE){
                out.collect(Tuple2.of(acc.first,"1"));
            }
            if (acc.second!=Integer.MIN_VALUE){
                out.collect(Tuple2.of(acc.second,"2"));
            }


        }

    }
}
